package edu.chen.controller;


import edu.chen.bean.User;
import edu.chen.service.impl.UserServiceImplByHibernate;
import edu.chen.util.CookieUtils;
import org.hibernate.annotations.Source;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller("userController")
public class UserController {

    private UserServiceImplByHibernate userServiceImplByHibernate;

    @Autowired
    //Qualifier制定需要注入的Bean的名称
    @Qualifier("userServiceImplByHibernate")
    public void setUserServiceImplByHibernate(UserServiceImplByHibernate userServiceImplByHibernate) {
        this.userServiceImplByHibernate = userServiceImplByHibernate;
    }

    @RequestMapping("/login")
    public String loginView(){
        return "login";
    }


    @RequestMapping(value = "/verifyLogin",method = RequestMethod.POST)
    /**
     * 使用@ResponseBody注解可以使返回的结果跳过视图处理阶段，而是调用适合HttpMessageConverter，将返回值写入输出流。
     * 若使用PrintWriter形式输出的数据则不需要该注解
     */
    @ResponseBody
    /**
     * 通过post形式发送的数据,可以于方法签名中的参数绑定.
     * 默认在JSON数据里面和KEY符合的绑定
     * @ModeAttribute
     * 该注解用于指定数据绑定
     */
    public String loginResult(@ModelAttribute("user") String username, @ModelAttribute("pass") String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        JSONObject jsonObject = new JSONObject();
        if (userServiceImplByHibernate.verifyUser(user)){
            request.getSession().setAttribute("loginUser",user);
            /**
             * 存储Cookie到本地浏览器
             */
            new CookieUtils().saveCookie(response,"autoLogin",username+"#"+password);
            jsonObject.put("result","success");
            jsonObject.put("redirect","index.jsp");
        }else{
            jsonObject.put("result","error");
        }
//        PrintWriter printWriter = response.getWriter();
//        printWriter.write(jsonObject.toString());
//        printWriter.flush();
//        printWriter.close();
        return jsonObject.toString();
    }
}
